import { NextRequest, NextResponse } from "next/server";
import { SqliteDatabase } from "@/lib/sqlite-database";

export async function POST(request: NextRequest) {
  try {
    const database = new SqliteDatabase();
    const db = database['db'];
    
    console.log("开始重置设备表ID...");
    
    // 重置设备表ID
    db.exec(`
      CREATE TEMPORARY TABLE temp_devices AS
      SELECT name, classification_name, classification_code, specialty, 
             naming_table_id, position_table_id, base_params_table_id, 
             tech_spec_table_id, sequence_number, remarks, 
             created_at, updated_at
      FROM devices
      ORDER BY id;

      DELETE FROM devices;
      DELETE FROM sqlite_sequence WHERE name='devices';

      INSERT INTO devices (
        name, classification_name, classification_code, specialty,
        naming_table_id, position_table_id, base_params_table_id,
        tech_spec_table_id, sequence_number, remarks,
        created_at, updated_at
      )
      SELECT name, classification_name, classification_code, specialty,
             naming_table_id, position_table_id, base_params_table_id,
             tech_spec_table_id, sequence_number, remarks,
             created_at, updated_at
      FROM temp_devices;

      DROP TABLE temp_devices;
    `);
    
    const deviceCount = db.prepare('SELECT COUNT(*) as count FROM devices').get() as { count: number };
    const minDeviceId = db.prepare('SELECT MIN(id) as min_id FROM devices').get() as { min_id: number };
    
    console.log(`设备表重置完成，总计 ${deviceCount.count} 行`);
    
    console.log("开始重置参数表ID...");
    
    // 重置基础参数表ID
    console.log("重置基础参数表ID...");
    
    // 1. 创建临时表
    db.exec(`
      CREATE TEMPORARY TABLE temp_base_parameters AS 
      SELECT device_id, parameter_name, example_description, data_type, measurement_class, data_source, created_at, updated_at 
      FROM base_parameters 
      ORDER BY device_id, parameter_name
    `);
    
    // 2. 清空原表
    db.exec('DELETE FROM base_parameters');
    
    // 3. 重置自增序列
    db.exec("DELETE FROM sqlite_sequence WHERE name='base_parameters'");
    
    // 4. 重新插入数据
    db.exec(`
      INSERT INTO base_parameters (device_id, parameter_name, example_description, data_type, measurement_class, data_source, created_at, updated_at)
      SELECT device_id, parameter_name, example_description, data_type, measurement_class, data_source, created_at, updated_at
      FROM temp_base_parameters
    `);
    
    // 5. 删除临时表
    db.exec('DROP TABLE temp_base_parameters');
    
    const baseCount = db.prepare('SELECT COUNT(*) as count FROM base_parameters').get() as { count: number };
    console.log(`基础参数表重置完成，总计 ${baseCount.count} 行`);
    
    // 重置位置参数表ID
    console.log("重置位置参数表ID...");
    
    db.exec(`
      CREATE TEMPORARY TABLE temp_position_parameters AS 
      SELECT device_id, parameter_name, parameter_value, data_type, example_description, measurement_class, data_source, is_required, created_at, updated_at 
      FROM position_parameters 
      ORDER BY device_id, parameter_name
    `);
    
    db.exec('DELETE FROM position_parameters');
    db.exec("DELETE FROM sqlite_sequence WHERE name='position_parameters'");
    
    db.exec(`
      INSERT INTO position_parameters (device_id, parameter_name, parameter_value, data_type, example_description, measurement_class, data_source, is_required, created_at, updated_at)
      SELECT device_id, parameter_name, parameter_value, data_type, example_description, measurement_class, data_source, is_required, created_at, updated_at
      FROM temp_position_parameters
    `);
    
    db.exec('DROP TABLE temp_position_parameters');
    
    const positionCount = db.prepare('SELECT COUNT(*) as count FROM position_parameters').get() as { count: number };
    console.log(`位置参数表重置完成，总计 ${positionCount.count} 行`);
    
    // 重置命名参数表ID
    console.log("重置命名参数表ID...");
    
    db.exec(`
      CREATE TEMPORARY TABLE temp_naming_parameters AS 
      SELECT device_id, parameter_name, parameter_value, data_type, example_description, measurement_class, data_source, is_required, created_at, updated_at 
      FROM naming_parameters 
      ORDER BY device_id, parameter_name
    `);
    
    db.exec('DELETE FROM naming_parameters');
    db.exec("DELETE FROM sqlite_sequence WHERE name='naming_parameters'");
    
    db.exec(`
      INSERT INTO naming_parameters (device_id, parameter_name, parameter_value, data_type, example_description, measurement_class, data_source, is_required, created_at, updated_at)
      SELECT device_id, parameter_name, parameter_value, data_type, example_description, measurement_class, data_source, is_required, created_at, updated_at
      FROM temp_naming_parameters
    `);
    
    db.exec('DROP TABLE temp_naming_parameters');
    
    const namingCount = db.prepare('SELECT COUNT(*) as count FROM naming_parameters').get() as { count: number };
    console.log(`命名参数表重置完成，总计 ${namingCount.count} 行`);
    
    // 验证ID重置结果
    const baseFirstId = db.prepare('SELECT MIN(id) as min_id FROM base_parameters').get() as { min_id: number };
    const positionFirstId = db.prepare('SELECT MIN(id) as min_id FROM position_parameters').get() as { min_id: number };
    const namingFirstId = db.prepare('SELECT MIN(id) as min_id FROM naming_parameters').get() as { min_id: number };
    
    console.log(`ID重置结果:`);
    console.log(`- 设备表: ${deviceCount.count} 行，最小ID: ${minDeviceId.min_id}`);
    console.log(`- 基础参数表: ${baseCount.count} 行，最小ID: ${baseFirstId.min_id}`);
    console.log(`- 位置参数表: ${positionCount.count} 行，最小ID: ${positionFirstId.min_id}`);
    console.log(`- 命名参数表: ${namingCount.count} 行，最小ID: ${namingFirstId.min_id}`);
    
    return NextResponse.json({
      success: true,
      message: "参数表ID重置成功",
      stats: {
        devices: {
          count: deviceCount.count,
          minId: minDeviceId.min_id
        },
        baseParameters: {
          count: baseCount.count,
          first_id: baseFirstId.min_id
        },
        positionParameters: {
          count: positionCount.count,
          first_id: positionFirstId.min_id
        },
        namingParameters: {
          count: namingCount.count,
          first_id: namingFirstId.min_id
        }
      }
    });
    
  } catch (error) {
    console.error("重置参数表ID时出错:", error);
    return NextResponse.json({ 
      success: false, 
      message: "重置参数表ID失败", 
      error: error instanceof Error ? error.message : String(error) 
    }, { status: 500 });
  }
} 